import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import RouteList from './config'
import store from "../store/index"
import NotFound from "../views/NotFound.vue"
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/mainBox',
    name: 'mainBox',
    component: () => import(/* webpackChunkName: "about" */ '../views/MainBox.vue'),
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound
  },
  // {
  //   path: '/:pathMatch(.*)*',
  //   name: 'CatchAll',
  //   redirect: '/404'
  // }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
const token = localStorage.getItem("token")
router.beforeEach( (to,from,next) => {
  // 去登录页面放行
  if( to.name == "login" ){
    next()
  }else{
      //没有token,重定向到login 
      if( !token ){
        next({path:"/login"})
      }
      // 有token 生成路由规则,放行
      else{
        // 第一次
        if( !store.state.loginState ){
          routerRule()
          next({path:to.fullPath}) 
        }
        // 不是第一次
        else{
          next()
        }
    
      }

  }
  
})
// 动态生成路由规则
function routerRule(){
  RouteList.forEach( item => {
    router.addRoute("mainBox",item)
  })
  // 改变
  store.commit("changeLoginState",true)
}

export default router
